import { isObject, isString } from '/@/utils/is';
import { SaaSResultEnum } from '/@/enums/httpEnum';
import type { RequestOptions, Result } from '/#/axios';
import { useMessage } from '/@/hooks/web/useMessage';
import { t } from '/@/hooks/web/useI18n';
const DATE_TIME_FORMAT = 'YYYY-MM-DD HH:mm:ss';
const { createMessage, createErrorModal } = useMessage();

export function joinTimestamp<T extends boolean>(join: boolean, restful: T): T extends true ? string : object;

export function joinTimestamp(join: boolean, restful = false): string | object {
  if (!join) {
    return restful ? '' : {};
  }
  const now = new Date().getTime();
  if (restful) {
    return `?_t=${now}`;
  }
  return { _t: now };
}

/**
 * @description: Format request parameter time
 */
export function formatRequestDate(params: Recordable) {
  if (Object.prototype.toString.call(params) !== '[object Object]') {
    return;
  }
  for (const key in params) {
    if ({}.hasOwnProperty.call(params, key)) {
      if (params[key] && params[key]._isAMomentObject) {
        params[key] = params[key].format(DATE_TIME_FORMAT);
      }
      if (isString(key)) {
        const value = params[key];
        if (value) {
          try {
            params[key] = isString(value) ? value.trim() : value;
          } catch (error: any) {
            throw new Error(error);
          }
        }
      }
      if (isObject(params[key])) {
        formatRequestDate(params[key]);
      }
    }
  }
}

export const slRspFormatter = function (response: Result, options: RequestOptions) {
  const { code, data, isSuccess, msg, errorMsg } = response;
  const hasSuccess = response && Reflect.has(response, 'code') && isSuccess && code === SaaSResultEnum.SUCCESS;
  if (hasSuccess) {
    if (data && data.constructor === Object && Reflect.has(data, 'records')) {
      const result = {
        total: Number(data.total),
        items: data.records,
      };
      return result;
    }
    return data || msg;
  } else {
    let popMsg = '';

    switch (code) {
      case SaaSResultEnum.FAIL || SaaSResultEnum.VALID_EX_CODE || SaaSResultEnum.OPERATION_EX_CODE:
        popMsg = msg;
        break;

      case SaaSResultEnum.TIMEOUTE:
        popMsg = '请求超时！';
        break;

      default:
        if (msg || errorMsg) {
          popMsg = msg || errorMsg;
        }
    }

    if (options.errorMessageMode === 'modal') {
      createErrorModal({ title: t('sys.api.errorTip'), content: popMsg });
    } else if (options.errorMessageMode === 'message') {
      createMessage.error(popMsg);
    }

    throw new Error(popMsg || t('sys.api.apiRequestFailed'));
  }
};
